<template>
  <div id="user-info-page">
    <div class="card-1">
      <a-avatar shape="square" class="avatar" :image-url="userInfo.avatar">
        <IconUser/>
      </a-avatar>
      <div class="info">
        <div class="username">
          {{ userInfo.nickname || '该用户还未填写昵称' }}
        </div>
        <div class="user-tab">
          <span @click="router.push(`/fans/${routeId}`)">粉丝：{{ userInfo.fans }}</span>
          <a-divider direction="vertical"/>
          <span @click="router.push(`/follow/${routeId}`)">关注：{{ userInfo.followee }}</span>
          <a-divider direction="vertical"/>
          <span>收藏：{{ userInfo.collect }}</span>
        </div>
        <div class="user-desc">
          {{ userInfo.userDesc || '该用户还未填写个人简介' }}
        </div>
      </div>
      <a-button
        v-if="!userInfo.followFlag" type="primary" class="edit-btn" @click="onClickFollow" :loading="followLoading">
        关注
      </a-button>
      <a-button v-if="userInfo.followFlag" type="outline" status="warning" class="edit-btn" @click="onClickUnFollow"
                :loading="unFollowLoading">
        取关
      </a-button>
    </div>

    <div class="card-container">
      <div class="card-2">
        <a-tabs default-active-key="1">
          <a-tab-pane key="1" title="收藏">
            <div v-if="collectAppList.length" class="app-list">
              <AppCard v-for="app in collectAppList" :key="app.id" :id="app.id" :appIcon="app.appIcon" :appName="app.appName"
                       :appDesc="app.appDesc" :user-id="app.userId" :avatar="app.avatar" :nickname="app.nickname"
                       :isCollected="app.collectFlag"/>
            </div>
            <div v-else class="no-data">
              <a-empty>暂无收藏应用</a-empty>
            </div>
            <div v-if="userInfo.collectAuth === 'HIDDEN'">
              <div class="no-data">
                <a-empty>该用户未开放收藏查看权限<template #image>
                  <IconStop/>
                </template></a-empty>
              </div>
            </div>
            <a-pagination
              size="small"
              :base-size="1"
              :buffer-size="1"
              :total="collectTotal"
              :default-page-size="collectPageSize"
              :current="collectCurrentPage"
              @change="handleCollectPageChange"
            />
          </a-tab-pane>
          <a-tab-pane key="2" title="应用">
            <div v-if="appList.length" class="app-list">
              <AppCard v-for="app in appList" :key="app.id" :id="app.id" :appIcon="app.appIcon" :appName="app.appName"
                       :appDesc="app.appDesc" :user-id="app.userId" :avatar="app.avatar" :nickname="app.nickname"
                       :isCollected="app.collectFlag"/>
            </div>
            <div v-else class="no-data">
              <a-empty>暂无应用</a-empty>
            </div>
            <div v-if="userInfo.appAuth === 'HIDDEN'">
              <div class="no-data">
                <a-empty>该用户未开放应用查看权限
                  <template #image>
                    <IconStop/>
                  </template>
                </a-empty>
              </div>
            </div>
            <a-pagination
              size="small"
              :base-size="1"
              :buffer-size="1"
              :total="total"
              :default-page-size="pageSize"
              :current="currentPage"
              @change="handlePageChange"
            />
          </a-tab-pane>
        </a-tabs>
      </div>
      <div class="card-3">
        <RecommendCard></RecommendCard>
      </div>
    </div>
  </div>
</template>

<script setup>
import { onMounted, ref } from 'vue';
import router from "@/router/index.js";
import { useUserStore } from "@/stores/index.js";
import { followUser, queryUserById, unfollowUser } from "@/api/user.js";
import { Message } from "@arco-design/web-vue";
import AppCard from "@/components/AppCard.vue";
import { queryAppPageByUserId } from "@/api/app.js";
import { pageQueryCollectAppByUserId } from "@/api/app.js";
import RecommendCard from "@/components/RecommendCard.vue";

const routeId = ref(0);
const userId = ref(0);
const userInfo = ref({
  id: '',
  nickname: '',
  gender: '',
  userDesc: '',
  avatar: '',
  collectAuth: '',
  appAuth: '',
  fans: '',
  followee: '',
  collect: '',
  followFlag: null
});

const followLoading = ref(false);
const unFollowLoading = ref(false);

const currentPage = ref(1);
const pageSize = ref(6);
const total = ref(0);
const appList = ref([]);

const collectCurrentPage = ref(1);
const collectPageSize = ref(6);
const collectTotal = ref(0);
const collectAppList = ref([]);

const getUserInfo = () => {
  const params = router.currentRoute.value.params;
  routeId.value = params.id;

  const userStore = useUserStore();
  userId.value = userStore.id;
  if (routeId.value === userId.value) {
    router.replace(`/user`);
    return;
  }

  queryUserById(routeId.value)
    .then(res => {
      if (res.data.code === 1) {
        userInfo.value = res.data.data;
        loadAppList();
        loadCollectAppList();
      } else {
        Message.error('获取用户信息失败');
      }
    })
    .catch(error => {
      console.error(error);
    });
};
getUserInfo();

const onClickFollow = () => {
  followLoading.value = true;
  followUser(routeId.value)
    .then(res => {
      if (res.data.code === 1) {
        if (res.data.data === true) {
          userInfo.value.followFlag = true;
          Message.success('关注成功');
        }
      }
    })
    .catch(error => {
      console.error(error);
    })
    .finally(() => {
      followLoading.value = false;
    });
};

const onClickUnFollow = () => {
  unFollowLoading.value = true;
  unfollowUser(routeId.value)
    .then(res => {
      if (res.data.code === 1) {
        if (res.data.data === true) {
          userInfo.value.followFlag = false;
          Message.success('取关成功');
        }
      }
    })
    .catch(error => {
      console.error(error);
    })
    .finally(() => {
      unFollowLoading.value = false;
    });
};

const loadAppList = async () => {
  if (userInfo.value.appAuth === 'HIDDEN') {
    Message.warning('该用户未开放应用查看权限')
    return
  }
  try {
    const res = await queryAppPageByUserId(routeId.value, {
      currentPage: currentPage.value,
      pageSize: pageSize.value
    });
    if (res.data.code === 1) {
      appList.value = res.data.data.records;
      total.value = Number(res.data.data.total)
    } else {
      Message.error('获取应用列表失败');
    }
  } catch (error) {
    console.error(error);
    Message.error('获取应用列表失败');
  }
};

const handlePageChange = (page) => {
  currentPage.value = page;
  loadAppList();
};

const loadCollectAppList = async () => {
  if (userInfo.value.collectAuth === 'HIDDEN') {
    Message.warning('该用户未开放收藏查看权限')
    return
  }
  try {
    const res = await pageQueryCollectAppByUserId(routeId.value, {
      currentPage: collectCurrentPage.value,
      pageSize: collectPageSize.value
    });
    if (res.data.code === 1) {
      collectAppList.value = res.data.data.records;
      collectTotal.value = Number(res.data.data.total)
    } else {
      Message.error('获取收藏应用列表失败');
    }
  } catch (error) {
    console.error(error);
    Message.error('获取收藏应用列表失败');
  }
};

const handleCollectPageChange = (page) => {
  collectCurrentPage.value = page;
  loadCollectAppList();
};

onMounted(() => {
  // 滚动到页面顶部
  window.scrollTo({
    top: 0,
    behavior: 'instant'
  });
});
</script>

<style scoped>
/* 用户信息卡片*/
.card-1 {
  position: relative;
  display: flex;
  padding: 20px;
  margin-top: 20px;
  height: auto;
  width: 100%;
  background-color: var(--color-bg-2);
  border-radius: 2px;
  border: 2px solid var(--color-neutral-2);
  color: var(--color-text-1);
}

.card-1 .avatar {
  height: 92px;
  width: 92px;
}

.card-1 .info {
  margin-left: 20px;
  font-size: 28px;
  font-weight: 600;
}

.card-1 .info .user-tab {
  margin-top: 10px;
  font-size: 14px;
  font-weight: 400;
  color: var(--color-text-2);
  cursor: pointer;
}

.card-1 .info .user-desc {
  margin-top: 10px;
  font-size: 16px;
  font-weight: 400;
  color: var(--color-text-2);
}

.card-1 .edit-btn {
  position: absolute;
  bottom: 20px;
  right: 20px;
}

.card-container {
  display: flex;
  justify-content: space-between;
  min-height: 60vh;
}

.card-2 {
  padding: 20px;
  margin-top: 20px;
  margin-right: 20px;
  height: auto;
  width: 80%;
  background-color: var(--color-bg-2);
  border-radius: 2px;
  border: 2px solid var(--color-neutral-2);
  color: var(--color-text-1);
}

.card-3 {
  padding: 20px;
  margin-top: 20px;
  height: auto;
  width: 20%;
  background-color: var(--color-bg-2);
  border-radius: 2px;
  border: 2px solid var(--color-neutral-2);
  color: var(--color-text-1);
}

.app-list {
  display: flex;
  justify-content: space-around;
  flex-wrap: wrap;
  gap: 20px;
  padding: 10px 0;
}

@media screen and (max-width: 768px) {
  .card-1 {
    position: relative;
    display: flex;
    padding: 10px;
    margin-top: 20px;
    height: auto;
    width: 100%;
    background-color: var(--color-bg-2);
    border-radius: 2px;
    border: 2px solid var(--color-neutral-2);
    color: var(--color-text-1);
  }

  .card-1 .avatar {
    height: 64px;
    width: 64px;
  }

  .card-1 .info {
    margin-left: 10px;
    font-size: 20px;
    font-weight: 600;
  }

  .card-1 .info .user-tab {
    margin-top: 5px;
    font-size: 10px;
    font-weight: 400;
    color: var(--color-text-2);
  }

  .card-1 .info .user-desc {
    margin-top: 5px;
    font-size: 12px;
    font-weight: 400;
    color: var(--color-text-2);
  }

  .card-1 .edit-btn {
    position: absolute;
    height: 20px;
    font-size: 12px;
    bottom: 10px;
    right: 10px;
  }

  .card-container {
    flex-direction: column;
  }

  .card-2 {
    width: 100%;
  }

  .card-3 {
    width: 100%;
  }
}
</style>
